package worker

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Bind(c *gin.Context) {
	_, err := util.AdminFilter(c)
	if err != nil {
		return
	}

	workerID, err := util.PostFormInt(c, "worker_id")
	if err != nil {
		return
	}
	seedID, err := util.PostFormInt(c, "seed_id")
	if err != nil {
		return
	}

	var nsqHost models.System
	if err := db.DB.Where("name = ?", models.SystemNsqHostName).
		Last(&nsqHost).Error; err != nil {
		util.FailedResponse(c, 10001, "获取nsq主机ip失败")
		return
	}

	nsqSetting := models.NsqSetting{
		Host:     nsqHost.Vale,
		WorkerID: uint(workerID),
		SeedID:   uint(seedID),
		Topic:    strconv.Itoa(seedID),
	}

	if err := db.DB.Create(&nsqSetting).Error; err != nil {
		util.FailedResponse(c, 10002, "绑定失败")
		return
	}

	c.JSON(200, gin.H{
		"status":  10000,
		"message": "success",
		"setting": nsqSetting,
	})
}

func BindCancel(c *gin.Context) {
	_, err := util.AdminFilter(c)
	if err != nil {
		return
	}

	settingID, err := util.PostFormInt(c, "setting_id")
	if err != nil {
		return
	}

	if err := db.DB.Delete(&models.NsqSetting{}, "id = ?", settingID).
		Error; err != nil {
		util.FailedResponse(c, 10001, "删除失败")
		return
	}

	util.SuccessResponse(c)
}
